import express from "express";
import cors from "cors";
import bodyParser from "body-parser";

import mysql from "mysql"
import dayjs from "dayjs";
import { createHash, } from "crypto";
import { v4 as uuidv4 } from "uuid";


import * as grpc from "@grpc/grpc-js";


//@ts-ignore
import Crypt from "node-jsencrypt"
import { AuthService, CheckTokenRes, CheckTokenResData, PrivateKey } from "../common";

const cache = new Map();

const connection = mysql.createConnection({
    host: 'localhost',
    user: 'root',
    password: '123456',
    database: 'mmodb'
});


const crypt = new Crypt();
crypt.setKey(PrivateKey);

const app = express();

app.use(cors());
app.use(bodyParser.json());


app.post('/register', function (req, res) {
    //console.log(req.body);

    let { account, password } = req.body;
    account = crypt.decrypt(account);

    password = crypt.decrypt(password);

    //console.log(account, password);

    const hash = createHash("md5");
    hash.update(password);

    const passwordHash = hash.digest("hex");


    connection.query(
        "insert into user (account, password, created_time)  VALUES (?,?,?)",
        [account, passwordHash, dayjs().format("YYYY-MM-DD HH:mm:ss")],
        function (error, results, fields) {
            if (error) {
                console.log("MySQL Error", error);
                return;
            };
            console.log(results);
            // ...
        });


    res.json({});
})

app.post('/login', function (req, res) {
    //console.log(req.body);

    let { account, password } = req.body;
    account = crypt.decrypt(account);

    password = crypt.decrypt(password);

    //console.log(account, password);

    const hash = createHash("md5");
    hash.update(password);

    const passwordHash = hash.digest("hex");


    connection.query(
        "select * from user where account =? and password =?",
        [account, passwordHash],
        function (error, results, fields) {
            if (error) {
                console.log("MySQL Error", error);
                return;
            };

            if (results.length > 0) {
                const token = uuidv4();
                cache.set(token, account);
                //console.log("cache: ", cache);
                console.log(account, "登录成功");
                res.json({ token });
            }
            else {
                res.json({ error: "账号或密码错误" });
            }
            // console.log("login results: ", results);
            // ...
        });


})

app.get('/', function (req, res) {
    res.send('Hello World,I am server');
})
app.listen(3000);

console.log("auth 服务");
// export default app;

const server = new grpc.Server();
server.addService(AuthService, {
    checkToken(call: any, callback: any) {

        const token = call.request.getToken();
        const res = new CheckTokenRes();

        if (cache.has(token)) {
            const data = new CheckTokenResData();
            data.setAccount(cache.get(token));
            res.setData(data);
        } else {
            res.setError("Token not exist");
        }

        callback(null, res);

    }
});

server.bindAsync("localhost:3333", grpc.ServerCredentials.createInsecure(), () => {

    server.start();
    console.log("RPC服务启动");

});